package com.bestcem.xm.user.grpc.client;

import com.alibaba.fastjson.JSON;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.om.grpc.v1.enums.EmailConfigTypeEnum;
import com.bestcem.xm.om.grpc.v1.services.*;
import com.bestcem.xm.user.enums.UserInnerFlagEnum;
import com.bestcem.xm.user.grpc.client.dto.IndustryPrincipalDTO;
import com.bestcem.xm.user.grpc.client.dto.OmUserDTO;
import com.bestcem.xm.user.grpc.client.dto.RelationDTO;
import com.bestcem.xm.user.grpc.client.dto.UserBookingDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * OM用户相关的服务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/10 11:43
 */
@Slf4j
@Service("userOmUserGrpcService")
public class OmUserGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;

    /**
     * 获取行业负责人
     *
     * @param industryId
     * @return IndustryPrincipalDTO
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/10 14:17
     */
    public IndustryPrincipalDTO getIndustryPrincipal(String industryId) {
        // 设置返回值
        IndustryPrincipalDTO industryPrincipalDTO = null;
        // 设置请求参数
        GetIndustryPrincipalRequest request = GetIndustryPrincipalRequest.newBuilder().setId(industryId).build();
        try {
            // 发送请求
            GetIndustryPrincipalResponse response = userServiceBlockingStub.getIndustryPrincipal(request);

            // 返回值处理
            if (Code.OK_VALUE == response.getStatus().getCodeValue()) {
                industryPrincipalDTO = IndustryPrincipalDTO.builder()
                        .id(response.getId())
                        .name(response.getName())
                        .build();

            } else if (Code.ERROR_VALUE == response.getStatus().getCodeValue()) {
                log.error("获取行业负责人失败. industryId: {}, response: {}", industryId, response.toString());
            }
        } catch (Exception e) {
            log.error("获取行业负责人失败. 发生异常.", e);
        }

        return industryPrincipalDTO;
    }

    /**
     * 关联公司的OM负责人和关联人
     *
     * @param orgId       公司id
     * @param principalOp 负责人id
     * @param relatedOps  关联人id 列表
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/10 14:13
     */
    public void createOrgRelatedOp(String orgId, String principalOp, List<String> relatedOps) {
        // 设置请求参数
        CreateOrgRelatedOpRequest request = CreateOrgRelatedOpRequest.newBuilder()
                .setOrgId(orgId)
                .setPrincipalOp(principalOp)
                .addAllRelatedOps(relatedOps)
                .build();

        try {
            // 发送请求
            CreateOrgRelatedOpResponse response = userServiceBlockingStub.createOrgRelatedOp(request);
            // 返回值处理
            if (Code.OK_VALUE != response.getStatus().getCodeValue()) {
                log.error("关联公司的OM负责人和关联人. response: {}", response.toString());
            }

        } catch (Exception e) {
            log.error("关联公司的OM负责人和关联人. 发生异常.", e);
        }
    }

    /**
     * 根据公司id获取负责人和关联人
     *
     * @param orgId 公司id
     * @return com.bestcem.xm.user.grpc.client.dto.RelationDTO
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/24 18:49
     */
    public RelationDTO getOrgRelatedOp(String orgId) {
        GetOrgRelatedOpRequest request = GetOrgRelatedOpRequest.newBuilder().setOrgId(orgId).build();
        RelationDTO relationDTO = new RelationDTO();
        try {
            GetOrgRelatedOpResponse response = userServiceBlockingStub.getOrgRelatedOp(request);
            relationDTO.setId(response.getPrincipalOp());
            relationDTO.setName(response.getPrincipalOpName());
            relationDTO.setRelationList(response.getRelatedOpsList());
        } catch (Exception e) {
            log.error("根据公司id获取负责人和关联人. 发生异常.", e);
        }
        return relationDTO;
    }


    /**
     * 获取单个OmUser
     *
     * @param userId
     * @return com.bestcem.xm.user.grpc.client.dto.OmUserDTO
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/25 09:40
     */
    public OmUserDTO getOmUser(String userId) {
        GetOmUserRequest request = GetOmUserRequest.newBuilder().setId(userId).build();
        OmUserDTO omUserDTO = new OmUserDTO();
        try {
            GetOmUserResponse response = userServiceBlockingStub.getOmUser(request);
            omUserDTO.setId(response.getOmUser().getId());
            omUserDTO.setEmail(response.getOmUser().getEmail());
            omUserDTO.setUsername(response.getOmUser().getUsername());
            omUserDTO.setStatus(response.getOmUser().getStatusValue());
            omUserDTO.setRealName(response.getOmUser().getName());
            omUserDTO.setRoleId(response.getOmUser().getRoleId());
            omUserDTO.setPhone(response.getOmUser().getPhone());
        } catch (Exception e) {
            log.error("根据公司id获取负责人和关联人. 发生异常.", e);
        }
        return omUserDTO;
    }

    /**
     * 根据orgId更新租户预约信息
     *
     * @param bookingDTO 预约信息
     * @return boolean 更新结果
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/07/09 21:22
     */
    public boolean updateBookingByOrgId(UserBookingDTO bookingDTO) {
        // 参数信息
        if (Objects.isNull(bookingDTO) || StringUtils.isEmpty(bookingDTO.getOrgId())) {
            log.error("根据orgId更新租户预约信息失败，orgId不能为空");
            return false;
        }

        // 构造入参信息
        UpdateBookingByOrgIdRequest.Builder builder = UpdateBookingByOrgIdRequest.newBuilder();
        builder.setOrgId(bookingDTO.getOrgId());
        if (StringUtils.isNotEmpty(bookingDTO.getCompanyName())) {
            builder.setCompanyName(bookingDTO.getCompanyName());
        }
        if (StringUtils.isNotEmpty(bookingDTO.getIndustryId())) {
            builder.setIndustryId(bookingDTO.getIndustryId());
        }
        if (StringUtils.isNotEmpty(bookingDTO.getPhone())) {
            builder.setPhone(bookingDTO.getPhone());
        }
        if (StringUtils.isNotEmpty(bookingDTO.getEmail())) {
            builder.setEmail(bookingDTO.getEmail());
        }

        UpdateBookingByOrgIdResponse response = userServiceBlockingStub.updateBookingByOrgId(builder.build());
        if (Code.OK_VALUE != response.getStatus().getCodeValue()) {
            log.error("根据orgId更新租户预约信息失败,dto:{},param:{}", response.getStatus().getMessage(), JSON.toJSONString(bookingDTO));
            return false;
        }

        return true;
    }


    /**
     * 根据通知类型获取通知邮箱配置
     *
     * @param notifyType 通知类型
     * @param emailType  邮件类型
     * @return java.util.List<java.lang.String>
     */
    public List<String> getOmEmailConfig(Integer notifyType, Integer emailType) {
        if (log.isInfoEnabled()) {
            log.info("根据type查询om配置的邮件列表参数：notifyType:{}，emailType:{}", notifyType, emailType);
        }

        GetOmEmailConfigRequest.Builder builder = GetOmEmailConfigRequest.newBuilder();
        EmailConfigTypeEnum.EmailConfigType emailConfigType = EmailConfigTypeEnum.EmailConfigType.forNumber(notifyType);
        builder.setType(emailConfigType);

        // 获取租户后台配置的通知邮箱
        GetOmEmailConfigResponse omEmailConfig = userServiceBlockingStub.getOmEmailConfig(builder.build());
        // 校验检查结果
        if (com.bestcem.bp.grpc.v1.base.Code.ERROR_VALUE == omEmailConfig.getStatus().getCodeValue()) {
            log.error("[USER]根据key查询om配置的邮件列表失败：dto:{}", omEmailConfig.getStatus().getMessage());
            return Collections.emptyList();
        }

        return UserInnerFlagEnum.INNER.getType().equals(emailType) ? omEmailConfig.getTestEmailsList() : omEmailConfig.getRealEmailsList();
    }

}
